package cn.ihoway.game;

import cn.ihoway.annotation.Processor;
import cn.ihoway.common.CommonProcessor;
import cn.ihoway.entity.Allocation;
import cn.ihoway.entity.Room;
import cn.ihoway.game.io.PlayerReadyInput;
import cn.ihoway.game.io.PlayerReadyOutput;
import cn.ihoway.redis.AllocationRedis;
import cn.ihoway.redis.RoomRedis;
import cn.ihoway.socket.GameSessionManager;
import cn.ihoway.type.StatusCode;
import cn.ihoway.util.HowayLog;
import cn.ihoway.util.HowayMessage;
import cn.ihoway.util.HowayWsResult;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 玩家准备 / 取消准备
 */
@Processor(name = "PlayerReadyProcessor")
public class PlayerReadyProcessor  extends CommonProcessor<PlayerReadyInput, PlayerReadyOutput> {
    private final HowayLog logger = new HowayLog(PlayerReadyProcessor.class);
    private final AllocationRedis allocationRedis = new AllocationRedis();
    private final RoomRedis roomRedis = new RoomRedis();

    @Override
    protected StatusCode dataCheck(PlayerReadyInput input){
        return StatusCode.SUCCESS;
    }
    
    @Override
    protected HowayWsResult process(PlayerReadyInput input, PlayerReadyOutput output) throws IOException {
        Allocation allocation = allocationRedis.getBySessionId(input.inChomm.sessionId);
        if(allocation == null){
            return HowayWsResult.createFailResult(StatusCode.ROOM_EMPTY,output);
        }
        if(allocation.getIsReady() == 0){
            allocation.setIsReady(1);
        }else {
            allocation.setIsReady(0);
        }
        allocationRedis.update(allocation);
        Room room = roomRedis.get(allocation.getRoomId());
        Integer currentNum = room.getCurrentNum();
        ArrayList<WebSocketSession> sessions = GameSessionManager.getFromRoom(allocation.getRoomId());
        for(WebSocketSession socketSession: sessions){
            if(allocation.getIsReady() == 1){
                HowayMessage message = new HowayMessage("用户" + input.inChomm.sessionId + "准备");
                socketSession.sendMessage(new TextMessage(message.toString()));
                if(allocationRedis.getReadyNums(room.getId()) == currentNum){
                    room.setStatus(1); //房主可以开始游戏
                    message = new HowayMessage("在线玩家都已准备");
                    socketSession.sendMessage(new TextMessage(message.toString()));
                }

            }else {
                room.setStatus(0);
                HowayMessage message = new HowayMessage("用户" + input.inChomm.sessionId + "取消准备");
                socketSession.sendMessage(new TextMessage(message.toString()));
            }
        }
        roomRedis.put(room.getId(),room);
        return HowayWsResult.createSuccessResult(output);
    }
}